/*----------------------------------------------------------------
// Copyright (C) 2011  博览财经资讯服务有限公司
// 版权所有
// 文件名：CommOp
// 文件功能描述：杂项操作,不涉及到Web页面功能
// 
// 创建标识:王家新
// 
// 修改标识：
// 修改描述：
//         
// 修改标识：
// 修改描述：
//----------------------------------------------------------------*/

using System;
using System.Data;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Text.RegularExpressions;

/// <summary>
/// 杂项操作,不涉及到Web页面功能
/// </summary>
namespace Aij1.Utils
{
    public static class CommOp
    {
        /// <summary>
        /// 生成Guid字符串,不带{}号
        /// </summary>
        /// <returns></returns>
        public static string NewId()
        {
            return Guid.NewGuid().ToString("D");
        }

        /// <summary>
        /// 判断是否是数字
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static bool IsNumeric(string str)
        {
            if (String.IsNullOrEmpty(str)) return false;
            System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
            byte[] bytestr = ascii.GetBytes(str);
            foreach (byte c in bytestr)
            {
                if (c < 48 || c > 57)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 获取一个字符串的字节长度
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static int ByteLength(string s)
        {
            return System.Text.Encoding.Default.GetByteCount(s);
        }

        #region 常见的类型转换
        /// <summary>
        /// 转换成Int32
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static int ToInt(object s)
        {
            int i = 0;
            if (s == null || s == DBNull.Value) return 0;
            if (int.TryParse(s.ToString(), out i)) return i;
            else return 0;
        }

        /// <summary>
        /// 转换成Int64
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static long ToLong(object s)
        {
            long i = 0;
            if (s == null || s == DBNull.Value) return 0;
            if (long.TryParse(s.ToString(), out i)) return i;
            else return 0;
        }

        /// <summary>
        /// 转换成float
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static float ToFloat(object s)
        {
            float i = 0f;
            if (s == null || s == DBNull.Value) return 0;
            if (float.TryParse(s.ToString(), out i)) return i;
            else return 0f;
        }

        /// <summary>
        /// 转换成decimal
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static decimal ToDecimal(object s)
        {
            decimal i = 0;
            if (s == null || s == DBNull.Value) return 0;
            if (decimal.TryParse(s.ToString(), out i)) return i;
            else return 0;
        }

        /// <summary>
        /// 转换成Double
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static Double ToDouble(object s)
        {
            Double f = 0f;
            if (s == null || s == DBNull.Value) return 0;
            if (Double.TryParse(s.ToString(), out f)) return f;
            else return 0f;
        }

        /// <summary>
        /// 转换成bool
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool ToBool(object s)
        {
            bool b = false;
            int i = 0;
            if (s == null || s == DBNull.Value) return false;
            if (bool.TryParse(s.ToString(), out b))
            { return b; }
            else if (int.TryParse(s.ToString(), out i))
            { return i != 0; }
            else return false;
        }

        /// <summary>
        /// 转换成string
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToStr(object s)
        {
            if (s == null || s == DBNull.Value) return "";
            return s.ToString().Trim();
        }

        /// <summary>
        /// 转换成Guid
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static Guid ToGuid(object s)
        {
            if (s == null || s == DBNull.Value || s == "") return Guid.Empty;
            return new Guid(ToStr(s));
        }

        /// <summary>
        /// 将整数的0转换成空串,其他原样转换
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String ToStr(int s)
        {
            return s == 0 ? String.Empty : s.ToString();
        }

        /// <summary>
        /// 将Decimal的0转换成空串,其他原样转换
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String ToStr(Decimal s)
        {
            return s == 0 ? String.Empty : s.ToString();
        }

        /// <summary>
        /// 将long的0转换成空串,其他原样转换
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String ToStr(long s)
        {
            return s == 0 ? String.Empty : s.ToString();
        }

        /// <summary>
        /// 原样转换字符串,不截空格
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToFullStr(object s)
        {
            if (s == null || s == DBNull.Value) return "";
            return s.ToString();
        }

        /// <summary>
        /// 截取指定长度字符串
        /// </summary>
        /// <param name="s"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string CutStr(String s, int len)
        {
            if (s == null) s = "";
            if (s.Length > len) s = s.Substring(0, len);
            return s;
        }

        /// <summary>
        /// 截取字符串,不足部分用...代替
        /// </summary>
        /// <param name="s"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string CutStrWithDot(object s, int len)
        {
            if (s == null || s == DBNull.Value) s = "";
            string str = ToStr(s);
            if (str.Length > len && len >= 4) str = str.Substring(0, len - 3) + "...";
            return str;
        }

        /// <summary>
        /// 将日期转换成yyyy-MM-dd或空串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToDateStr(object s)
        {
            if (s == null || s == DBNull.Value) return "";
            DateTime d;
            if (DateTime.TryParse(s.ToString(), out d))
            {
                return ToDateStr(d);
            }
            else
                return "";
        }

        /// <summary>
        /// 将日期转成yyyy-MM-dd或空串
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static String ToDateStr(DateTime d)
        {
            if (d == DateTime.MinValue) return "";
            return d.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 转换为yy/mm/dd形式的日期字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToDateStr2(object s)
        {
            if (s == null || s == DBNull.Value) return "";
            DateTime d;
            if (DateTime.TryParse(s.ToString(), out d))
            {
                if (d == DateTime.MinValue) return "";
                return d.ToString(@"yy/MM/dd");
            }
            else
                return "";
        }

        /// <summary>
        /// 将日期转换成yy-MM-dd HH:mm:ss格式的字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String ToTimeStr(object s)
        {
            if (s == null || s == DBNull.Value) return "";
            DateTime d;
            if (DateTime.TryParse(s.ToString(), out d))
            {
                if (d == DateTime.MinValue) return "";
                return d.ToString(@"yy-MM-dd HH:mm:ss");
            }
            else
                return "";
        }

        /// <summary>
        /// 将日期转换成yy-MM-dd HH:mm:ss格式的字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String ToTimeStr(DateTime d)
        {
            if (d == DateTime.MinValue) return "";
            return d.ToString(@"yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 将日期转换成MM-dd hh:mm格式的字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String ToTimeStr2(object s)
        {
            if (s == null || s == DBNull.Value) return "";
            DateTime d;
            if (DateTime.TryParse(s.ToString(), out d))
            {
                if (d == DateTime.MinValue) return "";
                return d.ToString(@"MM-dd HH:mm");
            }
            else
                return "";
        }

        /// <summary>
        /// 转换成DateTime?型
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static DateTime? ToDate(object s)
        {
            DateTime d;
            if (s == null || s == DBNull.Value || !DateTime.TryParse(s.ToString(), out d))
                return null;
            return d;
        }

        /// <summary>
        /// 转换成DateTime
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(object s)
        {
            DateTime d;
            if (s == null || s == DBNull.Value || !DateTime.TryParse(s.ToString(), out d))
                return default(DateTime);
            return d;
        }

        /// <summary>
        /// 将字符串分割成整数数组
        /// </summary>
        /// <param name="ints"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static int[] ToIntArray(string ints, char c)
        {
            string[] sArr = ints.Split(c);
            int[] iArr = new int[sArr.Length];
            for (int i = 0; i < iArr.Length; i++)
            {
                iArr[i] = CommOp.ToInt(iArr[i]);
            }
            return iArr;
        }

        /// <summary>
        /// 将字符串分割成长整数数组
        /// </summary>
        /// <param name="ints"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static long[] ToLongArray(string ints, char c)
        {
            string[] sArr = ints.Split(c);
            long[] iArr = new long[sArr.Length];
            for (int i = 0; i < sArr.Length; i++)
            {
                iArr[i] = CommOp.ToLong(sArr[i]);
            }
            return iArr;
        }

        //转换成至少2位小数格式，不足补0
        public static String ToNumStr2(object o)
        {
            if (o == null || o == DBNull.Value) return String.Empty;
            return String.Format("{0:0.00##}", o);
        }
        #endregion

        /// <summary>
        /// 将字符串加密MD5
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string MD5(string s)
        {
            string result = "";
            try
            {
                MD5 getmd5 = new MD5CryptoServiceProvider();
                byte[] targetStr = getmd5.ComputeHash(UnicodeEncoding.UTF8.GetBytes(s));
                result = BitConverter.ToString(targetStr).Replace("-", "");
                return result;
            }
            catch (Exception)
            {
                return "0";
            }
        }

        #region 将空值转换成数据库的空值
        /// <summary>
        /// 转换空串到DBNull.Value
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static object TestNull(String s)
        {
            if (s == null || s == "")
            {
                return DBNull.Value;
            }
            else
                return (object)s;
        }

        /// <summary>
        /// 转换对象到DBNull.Value
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static object TestNull(object s)
        {
            if (s == null || s.ToString() == "")
            {
                return DBNull.Value;
            }
            else
                return s;
        }

        /// <summary>
        /// 转换空日期到DBNull.Value
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public static object TestNull(DateTime d)
        {
            return d == DateTime.MinValue ? DBNull.Value : (object)d;
        }

        /// <summary>
        /// 转换0到DBNull.Value
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static object TestNull(int i)
        {
            if (i == 0) return DBNull.Value;
            else return (object)i;
        }

        /// <summary>
        /// 转换空值到DBNull.Value
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static object TestNull(decimal i)
        {
            if (i == 0) return DBNull.Value;
            else return (object)i;
        }
        #endregion

        /// <summary>
        /// 从Xml获取DataTable
        /// </summary>
        /// <param name="xmlFile"></param>
        /// <returns></returns>
        public static DataTable XmlToDataTable(string xmlFile)
        {
            DataSet ds = new DataSet();

            ds.ReadXml(xmlFile);
            DataTable dt = ds.Tables[0];
            return dt;
        }

        /// <summary>
        /// 将DataTable保存到Xml文件
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="xmlFile"></param>
        public static void DataTableToXml(DataTable dt, String xmlFile)
        {
            DataSet ds = dt.DataSet;
            if (ds == null)
            {
                ds = new DataSet();
                ds.Tables.Add(dt);
            }
            ds.WriteXml(xmlFile);
        }

        //截取字符长度;
        public static string Left(string str, int L)
        {
            string tmpStr;
            tmpStr = str;
            if (str.Length > L)
            {

                tmpStr = str.Substring(0, L);
            }
            return tmpStr;
        }

        /// <summary>
        /// 将纯文本转成HTML
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        public static string TextToHtml(string chr)
        {
            if (String.IsNullOrEmpty(chr)) return "";
            chr = chr.Replace("<", "&lt");
            chr = chr.Replace(">", "&gt");
            chr = chr.Replace("\n", "<br>");
            chr = chr.Replace(" ", "&nbsp;");
            return (chr);
        }

        /// <summary>
        /// 过滤Sql字符串
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static String FilterSql(String sql)
        {
            return sql.Replace("'", "''").Replace("--", "");
        }

        /// <summary>
        /// 比较两个值,o1&gt;o2返回1, o1=o2返回0, o1&lt;o2返回-1
        /// </summary>
        /// <param name="o1"></param>
        /// <param name="o2"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static int CompareValue(object o1, object o2, Type type)
        {
            if (o1 == DBNull.Value && o2 == DBNull.Value) return 0;
            if (o1 == DBNull.Value) return -1;
            if (o2 == DBNull.Value) return 1;

            if (o1 == null && o2 == null) return 0;
            if (o1 == null) return -1;
            if (o2 == null) return 1;

            int result = 0;
            if (type == null)
            {
                double d1, d2;
                if (Double.TryParse(o1.ToString(), out d1)
                    && Double.TryParse(o2.ToString(), out d2))
                {
                    return Math.Sign(d1 - d2);
                }
                else
                {
                    return String.Compare(ToStr(o1).PadLeft(20), ToStr(o2).PadLeft(20));
                }
            }
            switch (type.Name)
            {
                case "Int":
                case "Int32":
                case "Int64":
                case "Decimal":
                case "Short":
                case "Byte":
                    result = Decimal.Compare((decimal)o1, (decimal)o2);
                    break;
                case "Float":
                case "Double":
                    if ((Double)o1 > (Double)o2) { result = 1; break; }
                    if ((Double)o1 == (Double)o2) { result = 0; break; }
                    result = -1;
                    break;
                case "DateTime":
                    DateTime d1 = DateTime.MinValue;
                    DateTime d2 = DateTime.MinValue;
                    DateTime.TryParse(o1.ToString(), out d1);
                    DateTime.TryParse(o2.ToString(), out d2);
                    result = DateTime.Compare(d1, d2);
                    break;
                case "Boolean":
                    String i1 = "a", i2 = "a";
                    if ((Boolean)o1) i1 = "b";
                    if ((Boolean)o1) i2 = "b";
                    result = String.Compare(i1, i2);
                    break;
                default:
                    result = System.String.Compare(o1.ToString(), o2.ToString());
                    break;
            }
            return result;
        }

        /// <summary>
        /// 从文件读取字符串
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>读取的字符串</returns>
        public static String GetStringFromFile(String fileName)
        {
            using (StreamReader dataFuncHtml = new StreamReader(fileName, Encoding.UTF8))
            {
                String s = dataFuncHtml.ReadToEnd();
                dataFuncHtml.Close();
                return s;
            }
        }

        /// <summary>
        /// 保存字符串到文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="str">写入的字符串</param>
        public static void SaveStringToFile(String fileName, String str)
        {
            using (StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8))
            {
                sw.Write(str);
                sw.Close();
            }
        }

        /// <summary>
        /// 将Byte[]数组转换成Image对象
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Image BytesToImage(byte[] b)
        {
            if (b == null || b.Length == 0) return null;
            MemoryStream stream = new MemoryStream(b, true);
            stream.Write(b, 0, b.Length);
            return new Bitmap(stream);
        }

        /// <summary>
        /// 获取某文件夹全部指定了扩展名的文件名称(不包括扩展名)
        /// <param name="dirName">文件夹名称</param>
        /// <param name="extName">扩展名(含.号)</param>
        /// </summary>
        public static List<String> GetFileBaseNamesList(String dirName, String extName)
        {
            List<String> namesList = new List<string>();
            string[] files = Directory.GetFiles(dirName);

            foreach (string filename in files)
            {
                if (Path.GetExtension(filename).ToLower() == extName.ToLower())
                {
                    namesList.Add(Path.GetFileNameWithoutExtension(filename));
                }
            }
            return namesList;
        }

        private static string[] nearDayName = { "6-更早", "5-两天前", "4-昨天", "3-今天", "2-明天", "1-后天", "0-三天后" };
        /// <summary>
        /// 返回昨天、今天、前天等等
        /// </summary>
        /// <param name="dt">要获取的时间</param>
        /// <returns>昨天,今天之类的字符串</returns>
        public static String ToNearDayName(DateTime dt)
        {
            int days = (dt.Year * 365 + dt.DayOfYear) - (DateTime.Now.Year * 365 + DateTime.Now.DayOfYear);
            return ToNearDayName(days);
        }

        /// <summary>
        /// 返回昨天、今天、前天等等
        /// </summary>
        /// <param name="days"></param>
        /// <returns></returns>
        public static String ToNearDayName(int days)
        {
            days += 3;
            days = Math.Max(days, 0);
            days = Math.Min(days, 6);
            return nearDayName[days];
        }

        /// <summary>
        /// 通过反射生成指定类型对象
        /// </summary>
        /// <param name="fullClassName">类型全称</param>
        /// <returns></returns>
        public static object LoadClass(string fullClassName)
        {
            string[] names = fullClassName.Split(new char[] { ',' }, 2);

            if (names.Length == 1)
            {
                int i = fullClassName.LastIndexOf('.');
                string path = fullClassName.Substring(0, i);
                return Assembly.Load(path).CreateInstance(fullClassName);
            }
            else if (names.Length == 2)
            {
                return Assembly.Load(names[1]).CreateInstance(names[0]);
                //return Assembly.GetEntryAssembly().CreateInstance(names[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 带参数反射生成对象
        /// </summary>
        /// <param name="fullClassName"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static object LoadClass(string fullClassName, string param)
        {
            string[] names = fullClassName.Split(new char[] { ',' });

            Assembly ass = null;
            if (names.Length == 1)
            {
                int i = fullClassName.LastIndexOf('.');
                string path = fullClassName.Substring(0, i);
                ass = Assembly.Load(path);
            }
            else if (names.Length == 2)
            {
                fullClassName = names[0];
                ass = Assembly.Load(names[1]);
            }
            if (ass == null) return null;
            //Object obj = asm.CreateInstance("Reflection4.Calculator", true, BindingFlags.Default, null, parameters, null, null);

            return ass.CreateInstance(fullClassName, false, BindingFlags.Default, null, new object[] { param }, null, null);
        }

        #region 验证

        /// <summary>
        /// 判断是否是Email地址
        /// </summary>
        /// <param name="email">要判断的地址字符串</param>
        /// <returns>是否</returns>
        public static bool IsEmail(string email)
        {
            if (email == null) return false;
            return Regex.IsMatch(email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
        }

        /// <summary>
        /// 验证是否为汉子
        /// </summary>
        /// <param name="str_chinese"></param>
        /// <returns></returns>
        static public bool IsChinese(string strchinese)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(strchinese, @"^[\u4e00-\u9fa5]{0,}$");
        }

        /// <summary>
        /// 判断是否是电话号码
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public static bool IsPhoneNumber(string phoneNumber)
        {
            if (String.IsNullOrEmpty(phoneNumber)) return false;
            return Regex.IsMatch(phoneNumber, @"(\(\d{3}\)|\d{3}-)?\d{8}");
        }

        #endregion

        /// <summary>
        /// 判断是否含有除了字母及数字外的其他字符
        /// </summary>
        /// <param name="str">要验证的字符串</param>
        /// <returns>返回true代表包含汉字或者特殊字符</returns>
        public static bool StrIsNumberOrLetters(string str)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-z0-9]+$");
            if (regex.IsMatch(str))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 比较2个时间差
        /// </summary>
        /// <param name="currencyTime">当前的时间</param>
        /// <param name="contrastTime">要比较的时间</param>
        /// <returns></returns>
        public static int GetTimeDifference(DateTime currencyTime, DateTime contrastTime)
        {
            System.TimeSpan ts = contrastTime - currencyTime;
            return ts.Days; // 就是相差的天数
        }

        /// <summary>
        /// 清除HTML中的Tag标记，只留下文本。
        /// </summary>
        /// <param name="Htmlstring"></param>
        /// <returns></returns>
        public static string RemoveHTML(string html)
        {
            if (html == null) return "";
            string[] Regexs ={
                        @"<script[^>]*?>.*?</script>",
                        @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
                        @"([\r\n])[\s]+",
                        @"&(quot|#34);",
                        @"&(amp|#38);",
                        @"&(lt|#60);",
                        @"&(gt|#62);",
                        @"&(nbsp|#160);",
                        @"&(iexcl|#161);",
                        @"&(cent|#162);",
                        @"&(pound|#163);",
                        @"&(copy|#169);",
                        @"&#(\d+);",
                        @"-->",
                        @"<!--.*\n"
        };

            string[] Replaces ={
                            "",
                            "",
                            "",
                            "\"",
                            "&",
                            "<",
                            ">",
                            " ",
                            "\xa1", //chr(161),
                            "\xa2", //chr(162),
                            "\xa3", //chr(163),
                            "\xa9", //chr(169),
                            "",
                            "\r\n",
                            ""
        };

            for (int i = 0; i < Regexs.Length; i++)
            {
                html = new Regex(Regexs[i], RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(html, Replaces[i]);
            }
            html.Replace("<", "");
            html.Replace(">", "");
            html.Replace("\r\n", "");
            return html;
        }


        /// <summary>
        /// HTML转义符
        /// </summary>
        /// <param name="str">字符串</param>
        public static string ToHtmlStr(object s)
        {
            if (s == null || s == DBNull.Value) return "";
            return s.ToString().Replace("\r\n", "<br />").Replace("\n", "<br />");
        }

        /// <summary>
        /// 添加引号
        /// </summary>
        /// <param name="str">需要添加的字符串</param>
        /// <returns></returns>
        public static string AddQuotation(string str)
        {
            if (str != "")
            {
                StringBuilder sb = new StringBuilder();
                string[] strSplit = str.Split(',');
                str = "";
                for (int i = 0; i < strSplit.Length; i++)
                {
                    if (strSplit[i] != "")
                    {
                        //str += "'" + strSplit[i] + "',";
                        sb.Append("'" + strSplit[i] + "',");
                    }
                }
                if (sb.Length > 0)
                {
                    return sb.Remove(sb.Length - 1, 1).ToString();
                }
                //if (str != "")
                //    return str.Substring(0, str.Length - 1);
                //else
                return "";
            }
            else
                return "";
        }

        /// <summary>
        /// 获取系统临时目录
        /// </summary>
        /// <returns></returns>
        public static string GetTempDir()
        {
            string dir = Environment.GetEnvironmentVariable("TEMP");
            if (String.IsNullOrEmpty(dir))
                dir = "C:";
            return dir;
        }

        /// <summary>
        /// 将字符串转化成内存流
        /// </summary>
        /// <param name="str">要转的字符串</param>
        /// <returns>内存流</returns>
        public static Stream ToStream(string str)
        {
            byte[] strBytes = System.Text.Encoding.Default.GetBytes(str);
            MemoryStream ms = new MemoryStream();
            ms.Write(strBytes, 0, strBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }

        /// <summary>
        /// 将DataTable中数据写入到CSV文件中
        /// </summary>
        /// <param name="dt">提供保存数据的DataTable</param>
        /// <param name="fileName">CSV的文件路径</param>
        public static void SaveCSV(DataTable dt, string fileName)
        {
            FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
            string data = "";

            //写出列名称
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                data += dt.Columns[i].ColumnName.ToString();
                if (i < dt.Columns.Count - 1)
                {
                    data += ",";
                }
            }
            sw.WriteLine(data);

            //写出各行数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    data += dt.Rows[i][j].ToString();
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);
            }

            sw.Close();
            fs.Close();
        }


        /// <summary>
        /// 将CSV文件的数据读取到DataTable中
        /// </summary>
        /// <param name="fileName">CSV文件路径</param>
        /// <returns>返回读取了CSV数据的DataTable</returns>
        public static DataTable OpenCSV(string fileName)
        {
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
            //记录每次读取的一行记录
            string strLine = "";
            //记录每行记录中的各字段内容
            string[] aryLine;
            //标示列数
            int columnCount = 0;
            //标示是否是读取的第一行
            bool IsFirst = true;

            //逐行读取CSV中的数据
            while ((strLine = sr.ReadLine()) != null)
            {
                aryLine = strLine.Split(',');
                if (IsFirst == true)
                {
                    IsFirst = false;
                    columnCount = aryLine.Length;
                    //创建列
                    for (int i = 0; i < columnCount; i++)
                    {
                        DataColumn dc = new DataColumn(aryLine[i]);
                        dt.Columns.Add(dc);
                    }
                }
                else
                {
                    DataRow dr = dt.NewRow();
                    for (int j = 0; j < columnCount; j++)
                    {
                        dr[j] = aryLine[j];
                    }
                    dt.Rows.Add(dr);
                }
            }

            sr.Close();
            fs.Close();
            return dt;
        }

        /// <summary>
        /// 将流写入文件
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="path"></param>
        public static void WriteStreamToFile(Stream stream, string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                const int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];
                int count = 0;
                while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
                {
                    fs.Write(buffer, 0, count);
                }
                fs.Close();
                stream.Close();
            }
        }

        /// <summary>
        /// 过滤非法文件名字符
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string CheckFileName(string fileName)
        {
            fileName = Regex.Replace(fileName, "[|\\/,;:><=\\*\\?]+", "");
            return fileName;
        }

        /// <summary>
        /// 检查有无相同的文件，如果有，则返回一个后面加了(1),(2)...的文件名
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetUniqueFileName(string fileName)
        {
            FileInfo fi = new FileInfo(fileName);

            for (int i = 1; ; i++)
            {
                if (File.Exists(fileName))
                {
                    fileName = String.Format("{0}\\{1}({2}){3}", fi.DirectoryName, fi.Name.Substring(0, fi.Name.LastIndexOf('.')), i, fi.Extension);
                }
                else
                {
                    break;
                }
            }
            return fileName;
        }

        public static string GetFileExtName(string fileName)
        {
            FileInfo fi = new FileInfo(fileName);
            return fi.Extension;
        }
    }
}